package org.heart.springsecurity.springSecurity;


import org.heart.springsecurity.exceptions.CustomExceptions;
import org.heart.springsecurity.mapper.AuthenticationMapper;
import org.heart.springsecurity.pojo.Roles;
import org.heart.springsecurity.pojo.Users;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class AuthenticationUserDetailsService implements UserDetailsService {


    private final AuthenticationMapper authenticationMapper;


    public AuthenticationUserDetailsService(AuthenticationMapper authenticationMapper) {
        this.authenticationMapper = authenticationMapper;
    }
    /**
     * 账户密码
     */
    /**
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        Users users = authenticationMapper.getUser(username);
        if (Objects.isNull(users)) {
            throw new CustomExceptions.CustomUserNotFoundException("账号不存在");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        //查询权限集
        List<Roles> roles = authenticationMapper.getAuthorities(users.getUsersId());
        roles.forEach(role -> {
            authorities.add((GrantedAuthority) role::getRolesName);
        });

        return new AuthenticationUserDetails()
                .setUserId(Integer.parseInt(users.getUsersId()))
                .setUsername(users.getUsername())
                .setPassword(users.getPassword())
                .setAuthorities(authorities);
    }

    /**
     * 手机号
     *
     * @param phone
     * @return
     */
    public UserDetails loadUserByPhoneNumber(String phone) {


        Users loadUserByPhoneNumber = authenticationMapper.getLoadUserByPhoneNumber(phone);
        if (Objects.isNull(loadUserByPhoneNumber)) {
            throw new CustomExceptions.CustomUserNotFoundException("账号不存在");
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        //查询权限集
        List<Roles> roles = authenticationMapper.getAuthorities(loadUserByPhoneNumber.getUsersId());
        roles.forEach(role -> {
            authorities.add((GrantedAuthority) role::getRolesName);
        });

        return new AuthenticationUserDetails()
                .setUserId(Integer.parseInt(loadUserByPhoneNumber.getUsersId()))
                .setUsername(loadUserByPhoneNumber.getUsername())
                .setPassword(loadUserByPhoneNumber.getPassword())
                .setAuthorities(authorities);

    }


}
